<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from "vue";
import * as echarts from "echarts";
import { defineProps } from "vue";
import api from "@/api";
import { useScreenStore } from "@/store/modules/screen";
// 1. 定义父组件传递的 props
const props = defineProps({
  data: {
    type: Array,
    default: () => [
      { value: 1048, name: "脱尾主纱" },
      { value: 735, name: "敬酒礼服" },
      { value: 580, name: "迎宾礼服" },
      { value: 484, name: "晨袍" },
    ],
  },
});

const chartRef = ref(null);
let chartInstance = null;

// 2. 封装初始化图表的函数（复用）
const initChart = (datas) => {
  if (chartInstance) chartInstance.dispose(); // 销毁旧实例
  chartInstance = echarts.init(chartRef.value);

  // 计算总数
  const totalCount = chartData.value.reduce((sum, item) => sum + item.value, 0);

  const option = {
    color: ["#FF9636", "#147DFF", "#20BF7D", "#F4502D"],
    title: [
      {
        text: "总计",
        left: "75%",
        textAlign: "center",
        textVerticalAlign: "middle",
        top: "30%",
        textStyle: {
          fontSize: 12,
          color: "#8C8C8C",
        },
      },
      {
        // 成交金额文本
        text: totalCount.toLocaleString(),
        left: "75%",
        top: "56%",
        textAlign: "center",
        textVerticalAlign: "middle",
        textStyle: {
          fontSize: 24,
          color: "#262626",
          lineHeight: 36,
        },
      },
    ],
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)",
    },
    legend: {
      show: true,
      left: 0,
      top: "center",
      orient: "vertial", // 图例列表的布局朝向
      formatter: function (name) {
        const value = chartData.value.find((item) => item.name === name)?.value || 0;
        return `{name|${name}}\n{value|${value}}`;
      },
      itemGap: 10,
      itemWidth: 12,
      itemHeight: 12,
      textStyle: {
        rich: {
          name: {
            fontSize: 12,
            color: "#262626",
            padding: [16, 0, 0, 0],
          },
          value: {
            fontSize: 14,
            color: "#262626",
            padding: [3, 0, 0, 0],
          },
        },
      },
    },
    series: [
      {
        name: "",
        label: {
          show: false,
        },
        padAngle: 1,
        type: "pie",
        center: ["75%", "50%"],
        radius: ["60%", "80%"],
        data: chartData.value,
      },
    ],
  };
  chartInstance.setOption(option);
};

// 初始化screen store
const screenStore = useScreenStore();

// 创建计算属性，将customer_type_dic转换为图表数据格式
const chartData = computed(() => {
  const customerTypeData = screenStore.customer_type_dic;
  if (customerTypeData && Array.isArray(customerTypeData) && customerTypeData.length > 0) {
    return customerTypeData.map(item => ({
      name: item.key,
      value: item.value
    }));
  }
  // 如果没有数据，使用props.data或默认数据
  return props.data;
});

onMounted(() => {
  initChart(); // 组件挂载时初始化

  // 响应式resize
  const handleResize = () => chartInstance && chartInstance.resize();
  window.addEventListener("resize", handleResize);
  onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
    chartInstance && chartInstance.dispose();
  });

  // 打印customer_type_dic数据

});
//customer_province_dic	省份里的客户数量分布
// dealer_province_dic	省份里的 经销商 数量分布
// customer_type_dic	客户分类 数量分布
// instrument_category_dic	实验仪器百科 分类 数量分布
// equipment_category_dic	实验器材 分类 数量分布
// orders	图表的数据项
// equipments	图表的数据项

// 监听customer_type_dic数据变化并打印
watch(
  () => screenStore.customer_type_dic,
  (newData) => {

  },
  { deep: true }
);

// 监听chartData变化，重新渲染图表
watch(
  () => chartData.value,
  () => {
    initChart();
  },
  { deep: true }
);

watch(
  () => props.data,
  () => initChart()
);
</script>

<style scoped>
.chart-container {
  width: 100%;
  /* 自适应父容器宽度 */
  height: 100%;
}
</style>
